package com.thundersoft.beautifulmusic.other;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import android.widget.RemoteViews;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import com.thundersoft.beautifulmusic.R;
import com.thundersoft.beautifulmusic.entity.Song;
import com.thundersoft.beautifulmusic.util.Constants;
import com.thundersoft.beautifulmusic.util.SongUtil;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Random;

public class SongService extends Service {

    private RemoteViews mRemoteViews;
    private MusicHandler handler;

    private boolean isValidClick = true;

    private static final String TAG = "SongService";

    public SongService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 创建线程
        HandlerThread thread = new HandlerThread("service[music]");
        thread.start();
        handler = new MusicHandler(thread.getLooper());

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 通知渠道
        NotificationChannel channel = new NotificationChannel("music", "normal", NotificationManager.IMPORTANCE_DEFAULT);
        channel.setSound(null, null);
        mNotificationManager.createNotificationChannel(channel);
        Log.d(TAG, "onCreate: music service!");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        // 将intent放入子线程执行
        Message message = handler.obtainMessage();
        message.what = 1;
        message.obj = intent;
        handler.sendMessage(message);
        startForeground(10001, createMusicNotification(null, this));
        return super.onStartCommand(intent, flags, startId);
    }

    private Notification createMusicNotification(Song song, Context context) {
        return new NotificationCompat.Builder(context, "music")
                .setSmallIcon(R.mipmap.music_small_icon)
                .setWhen(System.currentTimeMillis())
                .setContent(getContentView(song, context))
                .setOngoing(true)
                .setAutoCancel(false)
                .build();
    }

    private RemoteViews getContentView(Song song, Context context) {
        if (song == null || context == null) {
            return null;
        }
        mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.notify_item);
        Bitmap bitmap = SongUtil.optimizeSongBitmap(song.getAlbumId());
        mRemoteViews.setImageViewBitmap(R.id.notify_cover, bitmap);
        mRemoteViews.setTextViewText(R.id.notify_song_name, song.getName());
        mRemoteViews.setTextViewText(R.id.notify_song_singer, song.getSinger());

        Intent lastIntent = new Intent(Constants.BroadCastAction.LAST_SONG);
        lastIntent.setPackage(context.getPackageName());
        lastIntent.putExtra("song", song);
        PendingIntent pi1 = PendingIntent.getBroadcast(context, 0, lastIntent, 0);
        mRemoteViews.setOnClickPendingIntent(R.id.notify_last, pi1);

        Intent i2 = new Intent(Constants.BroadCastAction.NOTIFICATION_PLAY_CLICK);
        i2.setPackage(context.getPackageName());
        mRemoteViews.setImageViewResource(R.id.notify_play, R.mipmap.pause);
        PendingIntent pi2 = PendingIntent.getBroadcast(context, 0, i2, 0);
        mRemoteViews.setOnClickPendingIntent(R.id.notify_play, pi2);

        Intent nextIntent = new Intent(Constants.BroadCastAction.NEXT_SONG);
        nextIntent.setPackage(context.getPackageName());
        PendingIntent pi3 = PendingIntent.getBroadcast(context, 0, nextIntent, 0);
        mRemoteViews.setOnClickPendingIntent(R.id.notify_next, pi3);
        return mRemoteViews;
    }

    @Override
    public void onDestroy() {
        stopForeground(true);
        super.onDestroy();
    }

    private class MusicHandler extends Handler implements MediaPlayer.OnPreparedListener {
        // 播放器
        private MediaPlayer mMediaPlayer;

        private int status = Constants.PlayerStatus.UNINITIALIZED;

        private Song currentSong;

        public MusicHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            Log.d(TAG, "currentThread = " + Thread.currentThread().getName());
            Intent intent = (Intent) msg.obj;
            int instruction = intent.getIntExtra("instruction", -1);
            Log.d(TAG, "handleMessage: instruction = " + instruction);
            if (status == Constants.PlayerStatus.UNINITIALIZED) {
                mMediaPlayer = new MediaPlayer();
                status = Constants.PlayerStatus.UNPREPARED;
            }
            switch (instruction) {
                case Constants.PlayerInstruction.PAUSE:
                    if (mMediaPlayer.isPlaying()) {
                        mMediaPlayer.pause();
                        status = Constants.PlayerStatus.PREPARED;
                    }
                    break;
                case Constants.PlayerInstruction.PLAY:
                    // 继续播放
                    mMediaPlayer.start();
                    status = Constants.PlayerStatus.PREPARED;
                    break;
                case Constants.PlayerInstruction.CHANGE:
                    Song song = (Song) intent.getSerializableExtra("song");
                    currentSong = song;
                    Log.d(TAG, "handleMessage: song = " + song.getName());
                    if (status == Constants.PlayerStatus.PREPARED) {
                        mMediaPlayer.reset();
                        status = Constants.PlayerStatus.UNPREPARED;
                    }
                    try {
                        mMediaPlayer.setDataSource(song.getPath());
                        mMediaPlayer.prepare();
                        mMediaPlayer.setOnPreparedListener(this);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onPrepared(MediaPlayer mp) {
            mMediaPlayer.start();
            status = Constants.PlayerStatus.PREPARED;
            startForeground(10001, createMusicNotification(currentSong, SongService.this));
        }
    }
}